package cn.gailvlun.gll.presentation.apartment.task;

import android.app.Activity;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;

import com.github.markzhai.recyclerview.BaseViewAdapter;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;

import cn.gailvlun.gll.R;
import cn.gailvlun.gll.bean.PlaceHolder;
import cn.gailvlun.gll.presentation.base.BaseActivity;
import cn.gailvlun.gll.databinding.ActivityTaskLibraryBinding;
import cn.gailvlun.gll.db.TaskDb;
import cn.gailvlun.gll.net.HttpMethods;
import cn.gailvlun.gll.net.HttpSubscriber;
import cn.gailvlun.gll.net.apartment.room.Task;
import cn.gailvlun.gll.bean.SelectHolder;
import cn.gailvlun.gll.presentation.apartment.task.adapter.TaskLibraryAdapter;
import cn.gailvlun.gll.util.DialogUtil;
import cn.gailvlun.gll.util.IsEmpty;
import cn.gailvlun.gll.util.RxUtil;
import cn.gailvlun.gll.util.ToastUtil;
import cn.gailvlun.gll.widget.NavigationBarView;
import io.reactivex.functions.Consumer;
import rx_activity_result2.Result;
import rx_activity_result2.RxActivityResult;



public class TaskLibraryActivity extends BaseActivity implements OnRefreshListener {

    public static void openActivity(Activity context, ArrayList<Integer> selectedId,
                                    Consumer<Result<Activity>> consumer) {
        Intent intent = new Intent(context, TaskLibraryActivity.class);
        intent.putIntegerArrayListExtra("selectedId", selectedId);
        RxActivityResult.on(context)
                .startIntent(intent)
                .subscribe(consumer);
    }


    private ActivityTaskLibraryBinding mBinding;
    private TaskLibraryAdapter mAdapter;
    private LinearLayoutManager mLayoutManager;

    @Override
    protected void initComponent() {
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_task_library);

        mAdapter = new TaskLibraryAdapter(mContext);
        mAdapter.setPresenter(new Presenter());
        mBinding.recyclerView.setAdapter(mAdapter);

        mLayoutManager = new LinearLayoutManager(mContext);
        mBinding.recyclerView.setLayoutManager(mLayoutManager);

        mBinding.refreshLayout.setOnRefreshListener(this);
        mBinding.refreshLayout.setEnableLoadmore(false);
    }

    @Override
    protected void createHandler() {
        mBinding.nbv.setOnBackListener(new NavigationBarView.OnBackListener() {
            @Override
            public void onBack(NavigationBarView nb) {
                onBackPressed();
            }
        });
        mBinding.nbv.setOnMenuClickListener(new NavigationBarView.OnMenuClickListener() {
            @Override
            public void onMenuClick(NavigationBarView nb) {
                ModifyTaskActivity.openActivity(mContext, null, new Consumer<Result<Activity>>() {
                    @Override
                    public void accept(Result<Activity> activityResult) throws Exception {
                        if (activityResult.resultCode() == RESULT_OK) {
                            mBinding.refreshLayout.autoRefresh(0);
                        }
                    }
                });
            }
        });
    }

    private ArrayList<Integer> selectedId;

    @Override
    protected void loadData(@Nullable Bundle savedInstanceState) {
        selectedId = getIntent().getIntegerArrayListExtra("selectedId");
        if (selectedId == null) {
            selectedId = new ArrayList<>();
        }

        
        List<Task> tasks = TaskDb.getInstance().getTasks();
        if (IsEmpty.list(tasks)) {
            mBinding.refreshLayout.autoRefresh(0);
        } else {
            loadRecyclerView(tasks);
        }
    }

    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        HttpMethods.getTemplateService()
                .getTemplateList()
                .compose(RxUtil.<List<Task>>applyScheduler())
                .subscribe(new HttpSubscriber<List<Task>>() {
                    @Override
                    protected void onSuccess(List<Task> response) {
                        loadRecyclerView(response);
                        mBinding.refreshLayout.finishRefresh(0);
                        TaskDb.getInstance().setTasks(response);
                    }

                    @Override
                    protected void onFailure(String errMsg, @Nullable List<Task> response, int code) {
                        DialogUtil.showError(mContext, errMsg);
                        mBinding.refreshLayout.finishRefresh(0);
                    }
                });
    }

    private void loadRecyclerView(List<Task> tasks) {
        mAdapter.clear();
        if (!IsEmpty.list(tasks)) {
            mAdapter.addAll(renderTaskList(tasks));
        }
    }

    private SelectHolder<Task> renderTask(Task res) {
        return new SelectHolder<>(res, selectedId.contains(res.getId()));
    }

    private List<SelectHolder<Task>> renderTaskList(List<Task> tasks) {
        List<SelectHolder<Task>> list = new ArrayList<>();
        for (Task task :
                tasks) {
            list.add(renderTask(task));
        }
        return list;
    }

    public class Presenter implements BaseViewAdapter.Presenter {
        public void onSelectTask(Task item) {
            Intent intent = new Intent();

            intent.putExtra("taskId", item.getId());
            setResult(RESULT_OK, intent);
            finish();
        }

        public void onModify(final Task item) {
            ModifyTaskActivity.openActivity(mContext, item, new Consumer<Result<Activity>>() {
                @Override
                public void accept(Result<Activity> activityResult) throws Exception {
                    if (activityResult.resultCode() == RESULT_OK) {
                        mBinding.refreshLayout.autoRefresh(0);
                    }
                }
            });
        }

        public void onDelete(Task item) {
            HttpMethods.getTemplateService()
                    .deleteTemplate(item.getId())
                    .compose(RxUtil.<PlaceHolder>applyScheduler())
                    .subscribe(new HttpSubscriber<PlaceHolder>() {
                        @Override
                        protected void onSuccess(PlaceHolder response) {
                            ToastUtil.showShort("删除成功");
                            mBinding.refreshLayout.autoRefresh(0);
                        }

                        @Override
                        protected void onFailure(String errMsg, @Nullable PlaceHolder response, int code) {
                            DialogUtil.showError(mContext, errMsg);
                        }
                    });
        }
    }

    public static class Util {
        public static int getSelectedVisibility(SelectHolder selectHolder) {
            if (selectHolder.getSelected() == null || !selectHolder.getSelected()) {
                return View.GONE;
            } else {
                return View.VISIBLE;
            }
        }
    }
}
